<template>
  <div>
    <!-- M面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="只能选择三级" type="warning" show-icon></el-alert>

      <el-row class="cat_opt">
        <el-col>
          <span>选择商品的分类:</span>
          <!-- 分类级联 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="CateChanged"
            clearable
            filterable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 动态静态标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isBtnDisabled" type="primary" @click="addParams">添加动态参数</el-button>
          <el-table :data="manyParamsData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环tag渲染 -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="tagClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="isBtnDisabled" type="primary" @click="addParams">添加静态属性</el-button>
          <el-table :data="onlyParamsData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="tagClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性对话框 -->
    <el-dialog
      :title="'添加'+ParamsTitie"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="ParamsTitie" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsPost">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑属性对话框 -->
    <el-dialog
      :title="'编辑'+ParamsTitie"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="ParamsTitie" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsPost">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类数据
      cateList: [],
      // 分类数据级联显示的值
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 分类数据级联被选中的值得value属性
      selectedKeys: [],
      // tabs选中的值
      activeName: 'only',
      // 静态动态获取保存的值
      onlyParamsData: [],
      manyParamsData: [],
      // 添加属性按钮的弹窗显示开关
      addParamsDialogVisible: false,
      // 编辑按钮弹窗显示开关
      editParamsDialogVisible: false,
      // 添加参数的表单数据对象
      addParamsForm: {
        attr_name: ''
      },
      // 编辑弹窗属性对象
      editParamsForm: {},
      // 添加表单的验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      // 编辑弹窗的验证规则
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 动态静态标签页中的按钮
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 选中分类的id值
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // addParamsTitle
    ParamsTitie() {
      if (this.activeName === 'only') {
        return '静态'
      }
      return '动态'
    }
  },
  methods: {
    // 获取分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.cateList = res.data
    },
    // 选中级联中属性的回调
    CateChanged() {
      this.getParamsData()
    },
    // 获取动态静态的数据
    async getParamsData() {
      // console.log(this.selectedKeys)
      // 如果选中的不等于3的时候
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.onlyParamsData = []
        this.manyParamsData = []
        return false
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      // 把返回的数据的字符串变成数组，添加tag的值
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // 保存数据
      if (this.activeName === 'only') {
        this.onlyParamsData = res.data
      } else {
        this.manyParamsData = res.data
      }
      // console.log(this.selectedKeys)
    },
    // 动态静态标签页回调
    handleClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 添加按钮点击回调
    addParams() {
      this.addParamsDialogVisible = true
    },
    // 关闭对话框时清空数据
    addDialogClosed() {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 添加弹窗点击确认发送请求
    addParamsPost() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addParamsDialogVisible = false
        this.getParamsData()
      })
    },
    // 编辑弹窗清空数据
    editDialogClosed() {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 编辑弹窗确认
    editParamsPost() {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        }
        this.editParamsDialogVisible = false
        this.getParamsData()
      })
    },
    // 点击编辑弹窗显示开关
    async showEditDialog(attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      // console.log(res)
      this.editParamsForm = res.data
      this.editParamsDialogVisible = true
    },
    // 根据Id删除对应的参数项
    async removeParams(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }
      this.$message.success('删除参数成功！')
      this.getParamsData()
    },
    // 添加tag失去焦点和按回车时的事件
    handleInputConfirm(scope) {
      // 输入空格的时候清空
      if (scope.inputValue.trim().length === 0) {
        scope.inputValue = ''
        scope.inputVisible = false
        return false
      }
      // 如果没有return
      scope.attr_vals.push(scope.inputValue.trim())
      scope.inputValue = ''
      scope.inputVisible = false

      this.saveTagVals(scope)
    },
    // tag发送请求
    async saveTagVals(scope) {
      // 发请求保存数据
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${scope.attr_id}`,
        {
          attr_name: scope.attr_name,
          attr_sel: scope.attr_sel,
          attr_vals: scope.attr_vals.join(' ')
        }
      )

      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // tag添加按钮的显示事件
    showInput(scope) {
      scope.inputVisible = true
      // $nextTick页面重新渲染后才会执行回调中的代码
      this.$nextTick(_ => {
        // 获取tag添加输入框的焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // tag删除事件
    tagClose(i, scope) {
      scope.attr_vals.splice(i, 1)
      this.saveTagVals(scope)
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 20px;
  span {
    margin-right: 9px;
  }
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
</style>
